import json
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, event):
        self.accept()

        group = self.scope['url_route']['kwargs'].get('group')
        print(f"群号{group} 用户名:{self.channel_name}")
        # 将客户的连接对象加入到某个地方 (内存 or redis)
        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

    def websocket_receive(self, message):
        msg = json.loads(message.get('text'))
        name = self.channel_name
        group = self.scope['url_route']['kwargs'].get('group')
        # 通知组中的所有客户端， 执行 xx_oo 方法
        async_to_sync(self.channel_layer.group_send)(
            group,
            {
                "type": "xx_oo",
                "message": msg.get('message'),
                "ImgUrl": msg.get('url'),
                "username": msg.get('username'),
                "name": name
            }
        )

    def xx_oo(self, event):
        if self.channel_name != event['name']:
            text = event["message"]
            self.send(text_data=json.dumps({"message": text, 'ImgUrl': event["ImgUrl"], 'username': event["username"]}))

    def websocket_disconnect(self, close_code):
        group = self.scope['url_route']['kwargs'].get('group')
        # 移除组中的人
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        # 断开当前客户端连接
        raise StopConsumer()
